<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use Endroid\QrCode\QrCode;
use think\facade\Env;

class Common extends Controller
{
    /**
     * 上传文件
     */
    public function upFile()
    {
        $file = request()->file('file');
        $info = $file->move( './uploads');
        if($info){
            $dir = '/uploads/'.str_replace("\\","/",$info->getSaveName());
            $this->success('上传成功!','',$dir);
        }else{
            $this->error($file->getError());
        }
    }

    /**
     * 富文本上传图片
     */
    public function kindUp()
    {
        $file = request()->file('imgFile');
        $info = $file->validate(['size'=>512000,'ext'=>'jpg,jpeg,png,gif'])->move( './uploads');
        if($info){
            $dir = Request()->domain().'/uploads/'.str_replace("\\","/",$info->getSaveName());
            echo json_encode(array('error' => 0, 'url' => $dir));
        }else{
            echo json_encode(array('error' => 1, 'message' => $file->getError()));
        }
    }

    /**
     * 生成二维码
     */
    public function qrcode($content,$name='',$subdir=''){
        $name = $name?:uniqid();//文件名
        $subdir = $subdir?:date('Ymd');//子目录
        $path = Env::get('ROOT_PATH').'public/qrcode/'.$subdir.'/'.$name.'.jpg';
        $dir = Env::get('ROOT_PATH').'public/qrcode/'.$subdir;
        if (!file_exists($dir)){
            mkdir($dir,0777,true);
        }
        $qrCode = new QrCode($content);
        //设置二维码大小
        $qrCode->setSize(200);
        //存储二维码
        $qrCode->writeFile($path);
        //返回二维码路径
        return '/qrcode/'.$subdir.'/'.$name.'.jpg';
    }

    //导出数据
    function downExcel($title,$field,$record,$file_name='file',$is_total=0,$count=1,$pos=['B','C','D'],$width=''){
        $num = count($field);
        if(!$width){//不传，单元格宽度默认为12
            $width = array_fill(0,$num,12);
        }
        $lastletter = chr(64+$num);
        // 创建Excel文件对象
        $objPHPExcel = new \PHPExcel();
        //表的样式
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        //设置字体字号
        $objPHPExcel->getDefaultStyle()->getFont()->setName('宋体');
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
        //单元格居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        //顶部标题
        $objPHPExcel->getActiveSheet()->mergeCells("A1:{$lastletter}1");
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //加上边框
        $objPHPExcel->getActiveSheet()->getStyle("A1:{$lastletter}1")->applyFromArray($styleArray);
        //全局行高
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);
        //标题行高
        $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(50);

        //添加表头
        for($i=0;$i<count($field);$i++){
            $letter = chr(65+$i);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$letter}2", $field[$i]);
            //加上边框
            $objPHPExcel->getActiveSheet()->getStyle("{$letter}2")->applyFromArray($styleArray);
            //自动换行
            $objPHPExcel->getActiveSheet()->getStyle("{$letter}2")->getAlignment()->setWrapText(TRUE);
            //表头行高
            $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(30);
            //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension("{$letter}")->setWidth($width[$i]);
        }

        //添加记录
        $j = 3;
        for ($c=1;$c<4;$c++){
            $name = 'total'.$c;
            $$name = '';
        }

        foreach ($record as $k=>$v){
            for($i=0;$i<count($field);$i++){
                $letter = chr(65+$i);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($letter.$j, array_values($v)[$i]);
                //加上边框
                $objPHPExcel->getActiveSheet()->getStyle($letter.$j)->applyFromArray($styleArray);
                //自动换行
                $objPHPExcel->getActiveSheet()->getStyle($letter.$j)->getAlignment()->setWrapText(TRUE);
            }
            $j++;
            if($is_total){
                for ($c=1;$c<$count+1;$c++){
                    $name = 'total'.$c;
                    $$name = $$name + array_values($v)[letterNum($pos[$c-1])];
                }
            }
        }

        if($is_total){
            //添加合计
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$j, '合计')
                ->setCellValue($pos[0].$j, $total1)
                ->setCellValue($pos[1].$j, $total2)
                ->setCellValue($pos[2].$j, $total3);
        }

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name.'.xls');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save("php://output");

    }

    //生成短链接
    public function shotLink($url){
        $host = "https://fshorturi.market.alicloudapi.com";
        $path = "/shortlink";
        $method = "GET";
        $appcode = "ec8eba4d549d4c508ff3c482c6a97a16";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "url=".$url;
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rst = curl_exec($curl);
        $rst = json_decode($rst,true);
        return $rst['url'];
    }
}
